package com.guli.edu.controller;


import com.guli.base.exception.GuliException;
import com.guli.edu.client.VodClient;
import com.guli.edu.entity.Video;
import com.guli.edu.entity.form.VideoForm;
import com.guli.edu.service.VideoService;
import com.guli.utils.R;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-09-27
 */

@Api(description = "课时管理")
//@CrossOrigin
@RestController
@RequestMapping("/edu/video")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private VodClient vodClient;

    // 添加课时
    @PostMapping("/addVideo")
    public R addVideo(@RequestBody VideoForm videoForm){
        videoService.saveVideo(videoForm);
        return R.ok();
    }

    // 查询课时
    @GetMapping("/getVideoForm/{id}")
    public R getVideoForm(@PathVariable String id){
        VideoForm videoForm = videoService.getVideoFormById(id);
        return R.ok().data("item",videoForm);
    }

    // 更新课时
    @PutMapping("/updateVideo/{id}")
    public R updateVideo(@RequestBody VideoForm videoForm,@PathVariable String id){
        videoService.updateVideoFormById(videoForm);
        return R.ok();
    }

    // TODO 课时的删除 追击 远程视频删除
    @DeleteMapping("/deleteVideo/{id}")
    public R deleteVideo(@PathVariable String id) {
        // 远程调用 vod 来删除视频
        Video video = videoService.getById(id);
        String videoSourceId = video.getVideoSourceId();
        R r = vodClient.removeVideo(videoSourceId);
        if (r.getCode() != 20000) {
            throw new GuliException(20001, "远程删除视频失败");
        }
        // 删除video表内容
        boolean flag = videoService.removeById(id);
        if(flag){
            return R.ok();
        }else{
            return R.error().message("删除课时失败");
        }
    }


}

